package com.ddmmo.exhibition.localBOSS.examination.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddmmo.exhibition.common.entity.Result;
import com.ddmmo.exhibition.localBOSS.examination.entity.po.KsAnswersPO;
import com.ddmmo.exhibition.localBOSS.examination.entity.po.KsExamsPO;
import com.ddmmo.exhibition.localBOSS.examination.entity.po.KsQuestionsPO;
import com.ddmmo.exhibition.localBOSS.examination.entity.ro.EndExamRO;
import com.ddmmo.exhibition.localBOSS.examination.entity.vo.AllHistoryVO;
import com.ddmmo.exhibition.localBOSS.examination.entity.vo.EndExamVO;
import com.ddmmo.exhibition.localBOSS.examination.entity.vo.StartExamVO;
import com.ddmmo.exhibition.localBOSS.examination.mapper.KsExamMapper;
import com.ddmmo.exhibition.localBOSS.examination.mapper.KsAnswerMapper;
import com.ddmmo.exhibition.localBOSS.examination.mapper.KsQuestionMapper;
import com.ddmmo.exhibition.localBOSS.examination.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 考试模块 - Service实现类
 * </p>
 *
 * @author JiangYiji
 * @since 2024/10/30
 */
@Service
public class ExamServiceImpl extends ServiceImpl<KsExamMapper, KsExamsPO> implements ExamService {

    @Autowired
    private KsExamMapper examMapper;

    @Autowired
    private KsAnswerMapper answerMapper;

    @Autowired
    private KsQuestionMapper questionMapper;

    /**
     * 开始考试
     */
    @Override
    public Result<StartExamVO> startExam(Integer questionFashionType) {

        List<KsQuestionsPO> singleChoiceQuestions = getQuestionsByTypeAndFashion(1, questionFashionType);
        List<KsQuestionsPO> multiChoiceQuestions = getQuestionsByTypeAndFashion(2, questionFashionType);
        List<KsQuestionsPO> trueFalseQuestions = getQuestionsByTypeAndFashion(3, questionFashionType);

        // 检查题库是否足够
        if (singleChoiceQuestions.size() < 2 || multiChoiceQuestions.size() < 2 || trueFalseQuestions.size() < 2) {
            Result.error("题库缺失，无法完成考试");
        }

        // 随机抽取题目
        List<KsQuestionsPO> selectedQuestions = new ArrayList<>();
        selectedQuestions.addAll(selectRandomQuestions(singleChoiceQuestions, 2));
        selectedQuestions.addAll(selectRandomQuestions(multiChoiceQuestions, 2));
        selectedQuestions.addAll(selectRandomQuestions(trueFalseQuestions, 2));

        StartExamVO startExamVO = new StartExamVO();
        startExamVO.setQuestionFashionType(questionFashionType);
        startExamVO.setKsAnswersPOList(selectedQuestions);

        return Result.success(startExamVO);
    }

    /**
     * 结束考试
     */
    @Override
    @Transactional
    public EndExamVO endExam(EndExamRO answers) {

        KsExamsPO ksExamsPO = new KsExamsPO();
        List<KsAnswersPO> ksAnswersPOList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 生成考试ID
        String examId = UUID.randomUUID().toString().replace("-", "");
        // 判分
        Double sumCount = 0.0;
        Double sumCountMax = 0.0;
        for (KsAnswersPO userAnswer : answers.getKsAnswersPOList()) {
            // 生成答案ID
            String answerID = UUID.randomUUID().toString().replace("-", "");
            userAnswer.setExamId(examId);
            userAnswer.setId(answerID);
            userAnswer.setUserAnswer(userAnswer.getUserAnswer());
            userAnswer.setCorrectAnswer(userAnswer.getCorrectAnswer());
            if (userAnswer.getUserAnswer().equals(userAnswer.getCorrectAnswer())) {
                userAnswer.setIsCorrect(0);
                sumCount = sumCount + userAnswer.getScore();
            }else {
                userAnswer.setIsCorrect(1);
            }
            sumCountMax = sumCountMax + userAnswer.getScore();
            // 插入用户答案到数据库
            answerMapper.insert(userAnswer);
            ksAnswersPOList.add(userAnswer);
        }
        ksExamsPO.setId(examId);
        ksExamsPO.setUserName(answers.getUserName());
        ksExamsPO.setTotalScore(sumCount);
        ksExamsPO.setTotalScoreMax(sumCountMax);
        ksExamsPO.setQuestionFashionType(answers.getQuestionFashionType());
        ksExamsPO.setExamDate(new Date());
        examMapper.insert(ksExamsPO);

        EndExamVO endExamVO = new EndExamVO();
        endExamVO.setQuestionFashionType(answers.getQuestionFashionType());
        endExamVO.setKsExamsPO(ksExamsPO);
        endExamVO.setKsAnswersPOList(ksAnswersPOList);
        return endExamVO;
    }


    /**
     * 查看历史记录
     */
    @Override
    public AllHistoryVO allHistory() {
        QueryWrapper<KsExamsPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("total_score");
        List<KsExamsPO> tigerRankingList = examMapper.selectList(queryWrapper);
        AllHistoryVO allHistoryVO = new AllHistoryVO();
        allHistoryVO.setTigerRankingList(tigerRankingList);
        return allHistoryVO;
    }

    // 辅助方法：筛选符合题目项
    private List<KsQuestionsPO> getQuestionsByTypeAndFashion(Integer questionType, Integer questionFashionType) {
        QueryWrapper<KsQuestionsPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_type", questionType)
                .eq("question_fashion_type", questionFashionType);
        return questionMapper.selectList(queryWrapper);
    }

    // 辅助方法：抽取题目
    private List<KsQuestionsPO> selectRandomQuestions(List<KsQuestionsPO> questions, int count) {
        Collections.shuffle(questions);
        return questions.stream().limit(count).collect(Collectors.toList());
    }

}
